package com.yc.jpyy.commonbusiness.controller;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.common.utils.manydatasource.HandlerDataSource;
import com.yc.jpyy.base.config.Config;
import com.yc.jpyy.base.controller.BaseController;
import com.yc.jpyy.utils.Tools;

@Controller
@RequestMapping(value = "/file")
@Scope("prototype")
public class GetFileListController extends BaseController{
	
	private static Logger logger = LoggerFactory
			.getLogger(GetFileListController.class);

	/**
	 * 获取某个文件夹底下所有文件的路径
	 * 
	 * @param request
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@SuppressWarnings("finally")
	@RequestMapping(value = "/getFileList", method = { RequestMethod.GET,
			RequestMethod.POST }, produces = "application/json; charset=utf-8")
	public @ResponseBody String getFileList(HttpServletRequest request)
			throws UnsupportedEncodingException {
		request.setCharacterEncoding("UTF-8");
		Map<String, Object> resultMap = new HashMap<>();
		try {
			String info = request.getParameter("info");
			Map<String, Object> paramsMap = Tools.JsonToMap(info);
			String fileName = (String) paramsMap.get("file");
			String rootPath = Config.getFilePath() + "\\";
			File file = new File(rootPath + fileName);
	        List<String> fileList = new ArrayList<>();
	        getAllFilePath(file,fileList);
	        if(fileList != null || fileList.size() > 0){
	        	fileList = fileList.stream().map(string-> 
                string.substring(rootPath.length()).replaceAll("\\\\", "/")).collect(Collectors.toList());
	        }
	        String result = String.join(";", fileList);
	        resultMap.put("ListData", result);
	        resultMap.put("returnCode", 1);
	        resultMap.put("returnMsg", "查询成功");
            resultMap.put("pubKey",Optional.ofNullable(request.getAttribute("pubKey")).orElse(""));
		} catch (Exception e) {
			logger.info("getFileList" + e.toString());
			resultMap.put("returnCode", 0);
			resultMap.put("returnMsg", "查询失败");
		} finally {
			HandlerDataSource.clear();
			return JSON.toJSONString(resultMap);
		}

	}
	
	/*
	 * java 递归获取一个目录下的所有文件路径
	 */
	public List<String> getAllFilePath(File file,List<String> resultFileName){
        File[] files = file.listFiles();
        if(files==null)return resultFileName;// 判断目录下是不是空的
        for (File f : files) {
            if(f.isDirectory()){// 判断是否文件夹
                //resultFileName.add(f.getPath());
                getAllFilePath(f,resultFileName);// 调用自身,查找子目录
            }else
                resultFileName.add(f.getPath());
        }
        return resultFileName;
    }
}
